import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import getuser from '../../../../atoms/getuser';
import { tbfduser, tbfdusergroup } from '../../../../atoms/db';

const logger = anylogger('pages/api/admin/groups/queryu.api');

export type Result = {
	users: ITbfduser[];
	selected: string[];
};

export type Query = {
	groupid: string;
}


/**
 * 获取用户数据服务
 */
const handler = an48<Result>();

handler.get(async (req, res) => {
	try {
		logger.debug('msg body:', req.query);
		const { groupid } = req.query as Query;
		logger.debug('groupid', groupid);
		//验证管理员用户
		const user = await getuser(req);
		if (!user || user.role !== 'admin') {
			logger.error('not allowed, please login as admin');
			res.status(200).json({
				selected: [],
				users: []
			});
			return;
		}
		//未获取到组别id
		if (!groupid) {
			res.status(200).json({
				selected: [] as string[],
				users: [] as ITbfduser[]
			});
			return;
		}
		//获取用户数据
		const dtuser = tbfduser();
		const d = await dtuser.select('*');
		const users = d.map((it) => {
			return {
				...it
			};
		});
		//获取已关联用户
		const userids = await (async () => {
			if (groupid) {
				const data = await tbfdusergroup()
					.select('userid')
					.where('groupid', '=', groupid);
				return data.map((it) => {
					return it.userid;
				});
			}
			return [] as string[];
		})();
		res.status(200).json({
			selected: userids,
			users
		});
	} catch (error) {
		logger.trace(error);
		logger.error(error);
		res.status(200).json({
			selected: [],
			users: []
		});
	}
});

export const config = {} as PageConfig;

export default handler;
